package gis.common;

import bean.ltecover.Building;
import gis.algorithm.GeoUtils;
import gis.algorithm.grid.GridUtils;
import org.apache.commons.lang.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Xiaobing on 2016/5/6.
 */
public class BuildingUtils {
    private static BuildingUtils instance = null;
    private Map<String, List<Building>> bmap = new HashMap<String, List<Building>>();
    private Map<String, Building> buildmap = new HashMap<String, Building>();
    private List<Building> builds = new ArrayList<Building>();

    /**
     * 建筑物
     *
     * @return
     */
    public List<Building> getBuilds() {
        return builds;
    }

    /**
     * 建筑物
     *
     * @param builds
     */
    public void setBuilds(List<Building> builds) {
        this.builds = builds;
    }

    /**
     * 获取实例
     *
     * @return
     */
    public static BuildingUtils GetInstance() {
        if (instance == null) {
            instance = new BuildingUtils();
        }
        return instance;
    }

    public int getCount() {
        return buildmap.size();
    }

    public void initbmap() {
        String key = "";
        for (Building b : builds) {
            try {
                key = GridUtils.getGridID(b.getExtent().getxMin(), b.getExtent().getyMin(), 0.01);
                if (!bmap.containsKey(key)) {
                    bmap.put(key, new ArrayList<Building>());
                }
                bmap.get(key).add(b);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void initbuildmap() {
        for (Building b : builds) {
            if (!buildmap.containsKey(b.getId())) {
                buildmap.put(b.getId(), b);
            }
        }
    }

    /**
     * 判断点是否在建筑物内
     *
     * @param x 经度
     * @param y 纬度
     * @return
     */
    public Building check(double x, double y) {
        String key = GridUtils.getGridID(x, y, 0.01);

        if (bmap.size() == 0) {
            initbmap();
        }

        if (bmap.containsKey(key)) {
            List<Building> bs = bmap.get(key);
            for (Building b : bs) {
                if (b.getExtent().contain(x, y)) {
                    if (GeoUtils.isPointInPolygon(b.getRing(), x, y)) {
                        return b;
                    }
                }
            }
        }
        return null;
    }

    /**
     * 根据ID 获取建筑物
     *
     * @param id 建筑物ID
     * @return
     */
    public Building getBuilding(String id) {
        if (buildmap.size() == 0) {
            initbuildmap();
        }
        Building b = buildmap.get(id);
        return b;
    }
}
